import Vue from 'vue'
import VueRouter from 'vue-router'
import layout from '@/layout'
import mainRoutes from './routes'
import store from '@/store'
import {
  loadMapScript
} from '@/utils'

Vue.use(VueRouter)

const routes = [{
  path: '/login',
  name: 'login',
  component: () => import('@/views/login')
}, {
  path: '/',
  component: layout,
  redirect: '/dashboard',
  children: [...mainRoutes]
}, {
  path: '*',
  name: '404',
  component: () => import('@/views/404')
}]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  const isLogin = store.state.app.isLogin
  if (to.name === 'login') {
    if (isLogin) {
      next('/dashboard')
    } else {
      next()
    }
  } else {
    if (!isLogin) {
      next('/login')
    } else {
      if (to.name === 'map-baidumap') {
        loadMapScript('baidu').then(() => {
          next()
        })
      } else if (to.name === 'map-qqmap') {
        loadMapScript('qq').then(() => {
          next()
        })
      } else {
        next()
      }
    }
  }
})

export default router
